<?
class Role extends Core
{
    private $_roleID="";
    private $_dataRow;
    private $_isNew = true;
    
    function __construct($roleID)
    {
        global $dbLink;
        $this->setDBLink($dbLink);
        $this->_roleID  = mysql_real_escape_string($roleID);
        $this->_dataRow =  new DataRow("users_roles", "roleID");
        $this->_isNew   = !($this->_dataRow->load($this->_roleID)); // si lo pudo cargar no es nuevo
    }
    function __get($prop) 
    {
        $item = "_".$prop;
        if(isset($this->$item)) return $this->$item;

        return $this->_dataRow->$prop;
    }
    function __set($prop, $val) 
    {
        $this->_dataRow->$prop = $val;
    }

    function save() 
    {
        $this->_dataRow->save();
        $this->_isNew = false;
    }
    
    function delete() {
        if($this->_roleID=="") return;
        $sql = "DELETE FROM users_roles_permissions WHERE roleID='".$this->_roleID."' ";        
        $this->_mysqlQuery($sql);
        $sql = "DELETE FROM users_roles WHERE roleID='".$this->_roleID."' ";        
        $this->_mysqlQuery($sql);
        return true;

    }

    function getModulePermissions($moduleID)
    {
        $sql = "SELECT permission FROM users_roles_permissions WHERE roleID='".$this->_roleID."' AND module='".$moduleID."'";
        $this->_mysqlQuery($sql, $result);
        $permissions = array();
        while($row = mysql_fetch_array($result)) $permissions[] = $row[0];
        return $permissions;        
        
    }
    function getUsers()
    {
        $sql = "SELECT username FROM users_users_roles JOIN users ON users.userID = users_users_roles.userID WHERE roleID='".$this->_roleID."'";
        $this->_mysqlQuery($sql, $result);
        $users = array();
        while($row = mysql_fetch_array($result)) $users[] = $row[0];
        return $users;        
        
    }

    function setModulePermissions($moduleID,$permissions)
    {
        if(!is_array($permissions)) return false;
        $this->_permissions = array();
        foreach($permissions as $permission)        
                $this->_permissions[] = mysql_real_escape_string($permission);
        $sql = "DELETE FROM users_roles_permissions WHERE roleID='".$this->_roleID."' AND module='".$moduleID."'";
                
        $this->_mysqlQuery($sql);
        
        if(count($permissions)==0) return;
        
        $sql = "INSERT INTO users_roles_permissions (roleID, module, permission) VALUES ";
        $values = array();
        foreach ($permissions as $p) 
        {
            $values[] = "('".$this->_roleID."','".$moduleID."','".$p."')";
        }
        $sql .= implode(",",$values);
        //echo $sql ."<br><br>";
        $this->_mysqlQuery($sql);
        
    }
}
?>
